
import { useNavigate } from 'react-router-dom';
import { BallsAddedInCart } from '../../components/ballsAddedInCart/ballsAddedInCart';
import Button from '../../components/button/button';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import styles from './cart.module.scss';
import { clearCart } from '../../store/cart/cart.slice';
import { fetchAddStoryBuySlice } from '../../store/buyStory/buyStory.action';

export const Cart = () => {
	const {balls} = useAppSelector(state => state.cart);
	const navigate = useNavigate();
	const totalSumm = balls.reduce((acc, item) => acc += item.count*item.price, 0);
	const dispatch = useAppDispatch();

	const addBuyOnStory = () => {
		dispatch(fetchAddStoryBuySlice({balls, totalSumm}));
		dispatch(clearCart());
		alert(`Зака оформлен на сумму ${totalSumm}`);
	};
	return (
		<div className={styles.container}>
			{balls.length === 0 ? 
				<div style={{textAlign: 'center'}}>
					<h2 style={{marginBottom: '20px'}}>Корзина пуста</h2>
					<Button onClick={() => navigate('/')}>К покупкам!</Button>
				</div>
				: 
				<>
					{balls.map(item => <BallsAddedInCart key={item.id} balls={item}/>)}
					<div className={styles.total}>
						<p>Сумма заказа: {totalSumm} руб.</p>
						<div className={styles.buttons}>
							<Button onClick={addBuyOnStory}>Оформить заказ</Button>
							<Button onClick={() => dispatch(clearCart())} deleted={true}>Очистить корзину</Button>
						</div>
					</div>
				</>
			}
			
		</div>
	);
};